import { nullEntity } from '$lib';
import { Types, addComponent, defineComponent, hasComponent, type Entity, type IWorld, removeEntity } from '$lib/ecs';

// TODO: use some OrderedMap?
const equipmentSlots = [];
export const equipmentMap = new Map();

export const defineEquipment = (cname, name) => {
  const comp = defineComponent(cname, {
    item: Types.eid,
  });
  equipmentSlots.push([name, comp]);
  equipmentMap.set(name, comp);
  return comp;
};

export const equip = (world, char, slot, e) => {
  const comp = equipmentMap.get(slot);
  if (!hasComponent(world, comp, char)) {
    addComponent(world, comp, char);
  }
  comp.item[char] = e;
};

export const unequip = (world, char, slot) => {
  comp.item[char] = nullEntity;
};

export const getEquipped = (world: IWorld, char: Entity) => {
  return equipmentSlots
    .filter(([_, comp]) => hasComponent(world, comp, char))
    .map(([name, comp]) => [name, comp.item[char]]);
};

export const getEquippedIn = (world: IWorld, char: Entity, slot: string) => {
  const comp = equipmentMap.get(slot);
  return comp.item[char];
};

export const purgeEquipment = (world: IWorld, char: Entity) => {
  for (let [_, comp] of equipmentSlots) {
    const item = comp.item[char];
    if (item !== nullEntity) {
      removeEntity(world, item);
      comp.item[char] = nullEntity;
    }
  }
};

export const HeadSlot = defineEquipment('HeadSlot', 'head');
export const HandsSlot = defineEquipment('HandsSlot', 'hands');
export const FeetSlot = defineEquipment('FeetSlot', 'feet');
export const LegsSlot = defineEquipment('LegsSlot', 'legs');
export const BodySlot = defineEquipment('BodySlot', 'body');
export const NeckSlot = defineEquipment('NeckSlot', 'neck');
export const MainHandSlot = defineEquipment('MainHandSlot', 'mainhand');
export const OffHandSlot = defineEquipment('OffHandSlot', 'offhand');
